/**
 * @file      ring_buffer.c
 * @brief     环形缓冲区
 * @author    Aki
 * @version   1.0
 * @date      2025-08-29
 */

#include "ring_buffer.h"
#include <stddef.h>

// 检查是否为2的N次方
static inline bool is_power_of_two(uint32_t n)
{
    return (n != 0) && ((n & (n - 1)) == 0);
}

bool rb_init(ring_buffer_t *rb, uint8_t *buffer, uint32_t size)
{
    if (rb == NULL || buffer == NULL || !is_power_of_two(size))
    {
        return false;
    }

    rb->buffer = buffer;
    rb->size = size;
    rb->head = 0;
    rb->tail = 0;

    return true;
}

void rb_reset(ring_buffer_t *rb)
{
    rb->head = 0;
    rb->tail = 0;
}

bool rb_write_byte(ring_buffer_t *rb, uint8_t byte)
{
    if (rb_is_full(rb))
    {
        return false; // 缓冲区已满
    }

    // 使用位掩码代替取模运算，提高效率
    rb->buffer[rb->head & (rb->size - 1)] = byte;
    rb->head++; // 利用uint32_t自然回绕

    return true;
}

uint32_t rb_write(ring_buffer_t *rb, const uint8_t *bytes, uint32_t size)
{
    uint32_t i;
    for(i = 0; i < size; i++)
    {
        if(rb_write_byte(rb, bytes[i]) == false) break; // 缓冲区已满
    }
    return i;
}

bool rb_read_byte(ring_buffer_t *rb, uint8_t *byte)
{
    if (rb_is_empty(rb))
    {
        return false; // 缓冲区为空
    }

    *byte = rb->buffer[rb->tail & (rb->size - 1)];
    rb->tail++;

    return true;
}

uint32_t rb_read(ring_buffer_t *rb, uint8_t *bytes, uint32_t size)
{
    uint32_t i;
    for(i = 0; i < size; i++)
    {
        if(rb_read_byte(rb, bytes + i) == false) break; // 缓冲区为空
    }
    return i;
}

uint32_t rb_get_data_size(const ring_buffer_t *rb)
{
    return (rb->head - rb->tail); // head-tail差值即为已用空间
}

uint32_t rb_get_free_size(const ring_buffer_t *rb)
{
    return (rb->size - rb_get_data_size(rb));
}

bool rb_is_full(const ring_buffer_t *rb)
{
    return (rb_get_data_size(rb) == rb->size);
}

bool rb_is_empty(const ring_buffer_t *rb)
{
    return (rb->head == rb->tail);
}
